package com.androway.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import android.util.Pair;

import com.androway.comparators.BookComparator;
import com.androway.domains.Book;
import com.androway.domains.BookReservation;
import com.androway.domains.Service;
import com.androway.services.Requester.OnResponseListener;
import com.androway.services.Requester.RequestType;
import com.androway.utils.Query;

public class LibraryModel extends AbstractModel
{
	private List<Book> bookList;

	public LibraryModel()
	{
		OnResponseListener requestListener = new OnResponseListener()
		{
			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(RequestType type, List<?> objects, String service)
			{
				if (type == RequestType.GET)
				{
					LibraryModel.this.bookList = (List<Book>) objects;
					Collections.sort(bookList, new BookComparator());
				}
				LibraryModel.this.listener.onSuccess(type, service);
			}

			@Override
			public void onError(RequestType type, String errorMessage)
			{
				LibraryModel.this.listener.onError(type, errorMessage);
			}
		};
		this.requester.setListener(requestListener);
	}

	public List<Book> getBooks()
	{
		return this.bookList;
	}

	public void loadBooks()
	{
		this.get(ApplicationModel.serverUrl + Service.Book, Book.class, Service.Book);
	}

	public List<Book> getMyReservation()
	{
		List<Book> books = new ArrayList<Book>();

		for (Book book : this.bookList)
			for (BookReservation reservation : book.getReservationList())
				if (reservation.getBorrower().getLogin().equals(ApplicationModel.getConnected().getLogin()))
				{
					books.add(book);
					break;
				}
		return books;
	}

	@SuppressWarnings("unchecked")
	public List<Book> searchByOccur(String str)
	{
		List<Book> occurences = new ArrayList<Book>();

		occurences.addAll((Collection<? extends Book>) Query.filter(Book.class, this.bookList, new Pair<String, String>("title", str), new Pair<String, String>("description", str), new Pair<String, String>("author", str)));
		return occurences;
	}
}
